﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class Drag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{


    Vector3 srcpos;
    public void Resume()
    {
        transform.position = srcpos;
    }

    public Transform current;
    public void OnBeginDrag(PointerEventData eventData)
    {
        srcpos = eventData.position;
        GameObject t = Instantiate(gameObject, transform.parent.parent.parent);
        t.transform.position = eventData.position;

        var arr = t.GetComponentsInChildren<Image>();
        t.name = arr[1].sprite.name;
        foreach (var img in arr)
        {
            img.raycastTarget = false;
        }
        current = t.transform;
        Drop.instance.gameObject.SetActive(true);
        Drop.instance.HighLightColor();
    }

    public void OnDrag(PointerEventData eventData)
    {
        if (current != null)
        {
            current.position = eventData.position;

            var obj = eventData.pointerCurrentRaycast.gameObject;
            var drop = obj?.GetComponent<Drop>();
            if (drop && drop.HasItem(current))
            {
                drop.RedColor();
            }
        }
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        var obj = eventData.pointerCurrentRaycast.gameObject;
        var drop = obj?.GetComponent<Drop>();
        if (null != drop)
        {
            drop.OnDrop(current);
        }

        Drop.instance.gameObject.SetActive(false);
        GameObject.Destroy(current.gameObject);
        current = null;

    }
}
